/**
 * @description 工具栏：查询组件
 * @author chenyan
 */

import React, { PropTypes, PureComponent } from 'react';
import { connect } from 'dva';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Select, Row, Col } from 'antd';
import { FirstHeaderC, QuickQueryC, TableC, XYAxisChartsC } from '../../../../../comps';
import style from './index.less';

const FormItem = Form.Item;
const formItemLayout = {
  labelCol: {
    span: 3,
  },
  wrapperCol: {
    span: 9,
  },
};

@Form.create()
class BondValuationChange extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      bondID: '',
      currentPage: 1, //当前页码
      numInPage: 10, //每页条数
      recommendValue: '4',
      initValue: '4',
      dataRange: '0',
      source: null,
    };
  }

  UNSAFE_componentWillReceiveProps(nextProps) {
    //判断是否是最新的bondID
    if (nextProps.bondID != this.state.bondID) {
      this.setState(
        {
          bondID: nextProps.bondID,
        },
        () => {
          this.props.form.resetFields();
          this.queryData();
        },
      );
    }
  }

  //页面销毁去缓存
  componentWillUnmount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'bondDeviationDetailM/setState',
      payload: {
        recommendData: [],
        norecommendData: [],
        valuationDetails: [],
        series: undefined, // y轴数据
        xAxis: undefined, // x轴日期数组
        valuationtype: null,
      },
    });
  }

  //请求表单数据
  queryData = () => {
    const { bondID } = this.state;
    const { dispatch } = this.props;
    const dataObj = sessionStorage.getItem('bondInfo') ? JSON.parse(sessionStorage.getItem('bondInfo')) : '';
    let newSource = '';
    if (this.state.source) {
      newSource = this.state.source;
    } else {
      newSource = 'first';
    }
    if (bondID) {
      dispatch({
        type: 'bondDeviationDetailM/setState',
        payload: {
          series: undefined, // y轴数据
          xAxis: undefined, // x轴日期数组
        },
      });
      dispatch({
        type: 'bondDeviationDetailM/valuationDetails',
        payload: {
          bondID: bondID,
          source: newSource, //如果不填，则根据后台查询的CLIENTCODE决定用哪个估值，并在返回值中告知前端  0：中债  1：上清  2：中证
          dataRange: this.state.dataRange, //0 : 近三个月  1 : 今年以来 默认是0
          currentPage: 1,
          numInPage: 500,
          tradingCode: dataObj.tradingCode,
          exchangeCode: dataObj.exchangeCode,
        },
      });
    }
  };

  //估值类型下拉切换
  valuationtypeChange = (e) => {
    const { dispatch } = this.props;
    this.setState(
      {
        source: e,
        currentPage: 1,
      },
      () => {
        dispatch({
          type: 'bondDeviationDetailM/setState',
          payload: {
            series: undefined, // y轴数据
            xAxis: undefined, // x轴日期数组
          },
        });
        this.setState({
          initValue: '4',
          recommendValue: '4',
        });
        this.queryData();
      },
    );
  };

  //推荐和不推荐切换
  recommendChange = (e) => {
    this.setState({
      recommendValue: e,
      initValue: e,
      currentPage: 1,
    });
  };

  //近3个月和今年以来切换
  showTimeChange = (e) => {
    const { dispatch } = this.props;
    this.setState(
      {
        dataRange: e,
        currentPage: 1,
      },
      () => {
        dispatch({
          type: 'bondDeviationDetailM/setState',
          payload: {
            series: undefined, // y轴数据
            xAxis: undefined, // x轴日期数组
          },
        });
        this.setState({
          initValue: '4',
          recommendValue: '4',
        });
        this.queryData();
      },
    );
  };

  //表格分页切换
  handleTableChange = (pagination, filter, sorter) => {
    const { current, pageSize } = pagination;
    this.setState({
      currentPage: current,
      numInPage: pageSize,
    });
  };

  //改变表格列
  changeColumns = (columns) => {
    const arr = columns;
    if (arr && arr.length) {
      arr.map((item) => {
        if (
          item.key == 'basispointval' ||
          item.key == 'convexity' ||
          item.key == 'evalutedyield' ||
          item.key == 'modiduration' ||
          item.key == 'netvaluation' ||
          item.key == 'termtomaturity'
        ) {
          item.align = 'right';
          item.render = (text, record) => {
            return !isNaN(text) ? Number(text).toFixed(4) : '--';
          };
        }
      });
    }

    return arr;
  };

  render() {
    const {
      loading,
      form: { getFieldDecorator },
    } = this.props;
    const {
      bondDeviationDetailM: { valuationDetails, recommendData, norecommendData, xAxis, series, valuationtype, max1, min1, max2, min2 },
    } = this.props;
    const { dataSource, pageInfo, columns } = valuationDetails;
    const newColumns = this.changeColumns(columns);
    const total = pageInfo ? pageInfo.total : 0;
    let disabled = [];
    if (recommendData.length == 0 && norecommendData.length == 0) {
      disabled = ['4', '5'];
    }
    if (recommendData.length == 0 && norecommendData.length > 0) {
      disabled = ['4'];
    }
    if (recommendData.length > 0 && norecommendData.length == 0) {
      disabled = ['5'];
    }
    if (recommendData.length > 0 && norecommendData.length > 0) {
      disabled = [];
    }
    return (
      <div>
        <Row type='flex' gutter={20}>
          <Col span={12} style={{ marginTop: '10px' }}>
            <FormItem label='估值类型' {...formItemLayout}>
              {getFieldDecorator('xyxt', {
                initialValue: valuationtype,
              })(
                <Select onChange={(e) => this.valuationtypeChange(e)} style={{ width: '250px' }}>
                  {[
                    { id: '0', name: '中债' },
                    { id: '1', name: '上清' },
                    { id: '2', name: '中证' },
                  ].map((item, i) => (
                    <Select.Option value={item.id} key={i}>
                      {item.name}
                    </Select.Option>
                  ))}
                </Select>,
              )}
            </FormItem>
          </Col>
          <Col span={12} style={{ marginTop: '15px' }}>
            <div className={style.right}>
              <QuickQueryC
                dataSource={[
                  { value: '0', title: '近30天' },
                  { value: '1', title: '今年以来' },
                ]}
                initialValue='0'
                onChange={(e) => this.showTimeChange(e)}
              />
            </div>
          </Col>
        </Row>

        <FirstHeaderC title='估值趋势' />
        <Row>
          <Col span={24}>
            <XYAxisChartsC
              series={series}
              xAxis={xAxis}
              height={400}
              yAxisUnit={['单位（%）']}
              yAxisRange={[
                [min2, max2],
                [min1, max1],
              ]}
              dataZoom={true}
            />
          </Col>
        </Row>

        <div style={{ marginTop: '13px' }}>
          <FirstHeaderC title='估值详情' />
        </div>

        <Row>
          <Col span={24}>
            <div className={style.right}>
              <QuickQueryC
                dataSource={[
                  { value: '4', title: '推荐' },
                  { value: '5', title: '不推荐' },
                ]}
                initialValue={this.state.initValue}
                disabled={disabled}
                onChange={(e) => this.recommendChange(e)}
              />
            </div>
          </Col>
          {/* <Col span={1} >
                        <div className={style.right}>
                            <PrimaryGhostC style={{ display: 'absloat' }} onClick={this.exportClick} title='导出' />
                        </div>
                    </Col> */}
        </Row>
        <Row style={{ marginTop: '10px' }}>
          {this.state.recommendValue == '3' ? (
            <TableC
              columns={newColumns}
              dataSource={dataSource || []}
              onChange={this.handleTableChange}
              current={this.state.currentPage}
              pageSize={this.state.numInPage}
              total={total}
              loading={loading}
              rowKey='id'
            />
          ) : this.state.recommendValue == '4' ? (
            <TableC
              columns={newColumns}
              dataSource={recommendData || []}
              onChange={this.handleTableChange}
              current={this.state.currentPage}
              pageSize={this.state.numInPage}
              total={recommendData.length || 0}
              loading={loading}
              rowKey='id'
            />
          ) : (
            <TableC
              columns={newColumns}
              dataSource={norecommendData || []}
              onChange={this.handleTableChange}
              current={this.state.currentPage}
              pageSize={this.state.numInPage}
              total={norecommendData.length || 0}
              loading={loading}
              rowKey='id'
            />
          )}
        </Row>
      </div>
    );
  }
}

export default connect(({ bondDeviationDetailM, loading }) => ({
  bondDeviationDetailM,
  loading: loading.effects['bondDeviationDetailM/valuationDetails'],
}))(BondValuationChange);
